=pod
 * Server.pm
 * 
 * Copyright (C) 2012 Elena Shishkina
 * 
 * This file is part of ServerInventory.
 * 
 * ServerInventory is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ServerInventory is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ServerInventory.  If not, see <http://www.gnu.org/licenses/>.
=cut

use utf8;
use 5.12.0;
package ServerInventory::Server;
use Moose;
use DBI;
use JSON;

sub Process {
    my $self = shift;
    my $r = shift;
    $self->{request} = $r;
    given ($r->param('mode')) {
        when ('edit') { $self->Edit }
        when ('remove') { $self->Remove }
        when ('add') { $self->Add }
        when ('full') { $self->FullData }
        when ('ips') { $self->GetIpList }
        default { $self->LoadData }
    }
}

sub FullData {
    my $self = shift;
    my $r = $self->{request};
    $r->{dbh}->sqlite_create_aggregate('agg_concat', 1, 'agg_concat');
    my $data = $r->{dbh}->selectall_arrayref(qq{select d.id as dc_id, d.name as dc, r.name as rack, i.*, v.name as vendor, v.color as vcolor, agg_concat(ip.ip) as srvip 
from inventory i 
left join racks r on r.id = i.rack_id
left join dcs d on d.id = r.dc_id
left join vendors v on i.vendor_id = v.id
left join server_ips ip on i.id = ip.server_id
group by i.id
order by dc, rack, i.name}, {Slice => {}}) || [];
    $r->render(json => $data);
}

sub GetIpList {
    my $self = shift;
    my $r = $self->{request};
    my $data = $r->{dbh}->selectall_arrayref(qq{select
i.ip,
coalesce(s.name, v.name, s.model) as cname,
s.name as name,
v.name as vendor,
s.model,
r.name as rack,
d.name as dc
from server_ips i
left join inventory s on i.server_id = s.id
left join vendors v on s.vendor_id = v.id
left join racks r on s.rack_id = r.id
left join dcs d on r.dc_id = d.id
order by 
		 CAST(PARSENAME(ip, 4) AS INT),
         CAST(PARSENAME(ip, 3) AS INT),
         CAST(PARSENAME(ip, 2) AS INT),
         CAST(PARSENAME(ip, 1) AS INT)}, {Slice => {}}) || [];
    $r->render(json => $data);
}

package agg_concat;

sub new {
    my $self = {};
    $self->{result} = '';
    bless $self, shift;
    return $self;
}

sub step {
    my ($self, $value) = @_;
    $self->{result} .= ',' if $self->{result};
    $self->{result} .= $value;
}

sub finalize {
    my $self = shift;
    return $self->{result};
}

1;
